﻿#include "QLuoshuApplication.h"

#include <Qtextstream>

static char* sDebugBuffer = NULL;
#define DEBUG_BUFFER_SIZE (1024 * 1024)


QLuoshuApplication::QLuoshuApplication(int &argc, char **argv)
        : QApplication(argc, argv),isDebuging(0),m_setting(0)
{

	m_pDebugAction = new QAction(tr("Debug..."), this);
	m_pDebugAction->setCheckable(true);
	m_pDebugAction->setStatusTip(tr("Open/Close Debug Window."));
	connect(m_pDebugAction, SIGNAL(triggered()), this, SLOT(openOrCloseDebugWin()));

	sDebugBuffer = new char[DEBUG_BUFFER_SIZE];

    m_setting = new QSettings(QLuoshuApplication::applicationDirPath() + "/qLuoshu.ini",QSettings::IniFormat);
}

QLuoshuApplication::~QLuoshuApplication()
{
	if(sDebugBuffer)
	{
		delete sDebugBuffer;
		sDebugBuffer = NULL;
	}

        delete m_setting;
        m_setting = 0;
}

void QLuoshuApplication::installDebugHandler()
{
	if(0 == isDebuging)
	{
		m_oldMsgHandler = qInstallMsgHandler(&this->userDebugHandler);
		m_pDebugAction->setChecked(true);
		isDebuging = 1;
	}
	else
	{
		//重置Msg句柄
		qInstallMsgHandler(m_oldMsgHandler);
		isDebuging = 0;
	}
}


void QLuoshuApplication::userDebugHandler(QtMsgType type, const char *pMsg )
{
	QString msg= "";

	switch ( type ) 
	{
	case QtDebugMsg:
        QTextStream(&msg) << "[Debug] " << pMsg << "\n";
		break;
	case QtWarningMsg:
        QTextStream(&msg) << "[Warning] " << pMsg << "\n";
		break;
	case QtCriticalMsg:
        QTextStream(&msg) << "[Critical] " << pMsg << "\n";
		break;
	case QtFatalMsg:
		abort(); 
	}

	if (qApp)
		((QLuoshuApplication*)qApp)->emitMySianal(type,msg);
}

void QLuoshuApplication::emitMySianal(QtMsgType type,QString sentence)
{
	emit incomingMsg(type,sentence);
}
